//
//  LiuComposeViewController.swift
//  LiuWeiBo
//
//  Created by 刘晓晨 on 2017/4/5.
//  Copyright © 2017年 刘晓晨. All rights reserved.
//

import UIKit
import SVProgressHUD

class LiuComposeViewController: UIViewController {
    
    //用来监听键盘是否为第一次弹出
    fileprivate lazy var  isfirstOut:Bool = true
    
    //懒加载控件
    fileprivate lazy var textView:LiuComposeTextView = {
        let textview = LiuComposeTextView()
        textview.font = UIFont.systemFont(ofSize: 14)
        textview.delegate = self
        textview.alwaysBounceVertical = true
        return textview
    }()
    
    fileprivate lazy var rightButton:UIButton = {
        let button = UIButton()
        button.setTitle("发送", for: .normal)
        button.setBackgroundImage(UIImage(named:"common_button_orange"), for: .normal)
        button.setBackgroundImage(UIImage(named:"common_button_orange_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named:"common_button_white_disable"), for: .disabled)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.darkGray, for: .disabled)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        button.size = CGSize(width: 45, height: 35)
        
        button.addTarget(self, action: #selector(sendAction), for: .touchUpInside)
        return button
    }()
    
    fileprivate lazy var titleView:UILabel = {
        let label = UILabel()
        if let name = LiuUserAccountViewModel.sharedUserAccountViewModel.userAccount?.name {
            let titleStr = "发微博\n" + name
            
            //获取名字的范围
            let range = (titleStr as NSString).range(of: name)
            
            //创建可变富文本
            let attributedStr:NSMutableAttributedString = NSMutableAttributedString(string: titleStr)
            
            //修改名字的大小颜色
            attributedStr.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12),NSForegroundColorAttributeName:UIColor.lightGray], range: range)
            
            //给label的富文本赋值
            label.attributedText = attributedStr
            
            //居中显示
            label.textAlignment = .center
            
            //自动换行
            label.numberOfLines = 0
        } else {
            label.text = "发微博"
        }
        label.sizeToFit()
        return label
    }()
    
    fileprivate lazy var toolBar:LiuComposeStackView = {
        let toolbar = LiuComposeStackView()
        toolbar.buttonActionClosure = { [weak self] (type:LiuComposeStackViewButtonType)->() in
            switch type {
            case .picture:
                //添加图片,模态出图片选择器
                print("我是图片选择")
                if let weakSelf = self {
                    weakSelf.didSelectedPicture()
                }
            case .mention:
            //添加图片,模态出图片选择器
                print("我是@")
            case .trend:
            //添加图片,模态出图片选择器
                print("我是#")
            case .emoticon:
            //添加图片,模态出图片选择器
                print("我是表情符")
                if let weakSelf = self {
                    weakSelf.didSelectedEmotion()
                }
            case .add:
            //添加图片,模态出图片选择器
                print("我是添加")
           
            }
        }
        
        return toolbar
    }()
    
    //懒加载图片view
    fileprivate lazy var picView:LiuComposePicView = {
        let picview = LiuComposePicView()
        
        //点击加号cell回调添加图片
        picview.addPicClosure = { [weak self] in
            self?.didSelectedPicture()
        }
        
        //图片张数改变回调
        picview.imageCountChangeClosure = { [weak self] (count)->() in
            //判断内容,改变right按钮的状态
            if (self?.textView.hasText)! || count != 0 {
                self?.navigationItem.rightBarButtonItem?.isEnabled = true
            } else {
                self?.navigationItem.rightBarButtonItem?.isEnabled = false
            }
        }
        return picview
    }()
    
    //懒加载表情键盘
    fileprivate lazy var emoticonKeyBoard:LiuEmoticonView = {
        let keydoard = LiuEmoticonView()
        keydoard.size = CGSize(width: self.textView.size.width, height: 216)
        return keydoard
    }()
    
    

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
    }
    
    fileprivate func setupUI() {
        
        view.backgroundColor = UIColor.white
        
        //添加控件
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(picView)
        
        //添加左侧item
        navigationItem.leftBarButtonItem = UIBarButtonItem(titleStr: "取消", andTarget: self, action: #selector(leftButtonAction))
        
        //右侧item
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem?.isEnabled = false
        
        //添加title
        navigationItem.titleView = titleView
        //约束
        textView.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.bottom.equalTo(toolBar.snp.top)
        }
        
        toolBar.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(35)
        }
        
        picView.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(100)
            make.centerX.equalToSuperview()
            make.width.equalToSuperview().offset(-2 * homeMargin)
            make.height.equalTo(view.width - 2 * homeMargin)
        }
        
        //监听键盘的frame改变
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardframeChanged(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
    }
    
    
    //左侧item"取消"
    @objc fileprivate func leftButtonAction() {
        //失去第一响应者
        //必须是控制器的根view去掉用,直接用titleView会有问题
        view.endEditing(true)
//        view.resignFirstResponder()
        dismiss(animated: true, completion: nil)
    }
    

    
    //发微博
    @objc fileprivate func sendAction() {
        
        let sendStr = textView.getAllString()
        
        if picView.picArray.count > 0 {
            LiuNetworkManager.sharedTools.sendWeiboWithImage(userAccount: LiuUserAccountViewModel.sharedUserAccountViewModel.userAccount!, text: sendStr, image: picView.picArray[0], compeleteCallBack: { (response, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发送失败")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "发送成功")
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: {
                    
                    self.textView.resignFirstResponder()
                })
                
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: {
                    
                    self.dismiss(animated: true, completion: nil)
                })
                
            })
        } else {
            LiuNetworkManager.sharedTools.sendWeiboOnlyText(userAccount: LiuUserAccountViewModel.sharedUserAccountViewModel.userAccount!, text: sendStr) { (response, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发送失败")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "发送成功")
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: {
                    
                    self.textView.resignFirstResponder()
                })
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: {
                    
                    self.dismiss(animated: true, completion: nil)
                })
                
            }
        }
        
    }
    
    //监听键盘的frame改变
    @objc fileprivate func keyboardframeChanged(noti:Notification) {
        let userinfo = noti.userInfo!
        let frame:CGRect = userinfo[UIKeyboardFrameEndUserInfoKey] as! CGRect
        let duration = userinfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
        
        //修改toolBar底部约束
        self.toolBar.snp.updateConstraints { (make) in
            make.bottom.equalToSuperview().offset(frame.origin.y - screenHeight)
        }
        
        //判断键盘是否为第一次弹出
        if isfirstOut {
            DispatchQueue.main.async {
                UIView.animate(withDuration: duration) {
                    self.view.layoutIfNeeded()
                }
            }
            
            isfirstOut = false
        } else {
            UIView.animate(withDuration: duration) {
                self.view.layoutIfNeeded()
            }
        }
        
        
        
        
    }
    
}

extension LiuComposeViewController {
    //处理tool按钮点击的逻辑
    
    //跳转到图片选择
    fileprivate func didSelectedPicture() {
        let imagePictureCtr = UIImagePickerController()
        imagePictureCtr.delegate = self
        
        //  判断来源, 一定要要上判断
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            //  真机运行使用相机
            imagePictureCtr.sourceType = .camera
        } else {
            //  模拟器运行使用图库
            imagePictureCtr.sourceType = .photoLibrary
        }
        
        //  扩展
        //  判断摄像头是否可用
        if UIImagePickerController.isCameraDeviceAvailable(.front) {
            print("前置设置头可用")
        }
        if UIImagePickerController.isCameraDeviceAvailable(.rear) {
            print("后者摄像头可用")
        }
        
        present(imagePictureCtr, animated: true, completion: nil)
        
    }
    
    //改变输入框
    fileprivate func didSelectedEmotion() {
        if textView.inputView == nil {
            //从原生键盘到表情键盘
            textView.inputView = emoticonKeyBoard
            toolBar.changeImage(isChange: true)
        } else {
            
            //从表情键盘到原生键盘
            textView.inputView = nil
            toolBar.changeImage(isChange: false)
        }
        
        //设置第一响应者
        textView.becomeFirstResponder()
        
        //重新加载inputView
//        UIView.animate(withDuration: 0.25) { 
//            self.textView.reloadInputViews()
//        }
        textView.reloadInputViews()
    }
    
}

extension LiuComposeViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        //移除图片选择器
        picker.dismiss(animated: true, completion: nil)
        
        //对图片做处理(防止内存暴涨)
        let currenImage = disposeImage(image: image)
        
        
        //将图片添加到picview的数组中
        picView.addImage(image: currenImage)
        
    }
    
    //处理图片
    fileprivate func disposeImage(image:UIImage) -> UIImage {
        
        //通过image调整新图片的size
        let newImageWidth:CGFloat = 200
        let newImageHeight = image.size.height * newImageWidth / image.size.width
        
        //开启图片上下文
        UIGraphicsBeginImageContext(CGSize(width: newImageWidth, height: newImageHeight))
        
        //见图片渲染到上下文中
        image.draw(in: CGRect(origin: CGPoint.zero, size: CGSize(width: newImageWidth, height: newImageHeight)))
        
        //获取上下文中的图片
        let newImage = UIGraphicsGetImageFromCurrentImageContext()!
        
        //关闭上下文
        UIGraphicsEndImageContext()
        
        return newImage
        
    }
}

extension LiuComposeViewController:UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        //判断内容,改变right按钮的状态
        if textView.hasText || picView.picArray.count != 0 {
            navigationItem.rightBarButtonItem?.isEnabled = true
        } else {
            navigationItem.rightBarButtonItem?.isEnabled = false
        }
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        
        //失去第一响应者
        textView.endEditing(true)
    }

}









